package com.cookie.framework.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.cookie.framework.helper.GlideHelper;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 项目名:    MeetProject
 * 包名:      com.cookie.framework.adapter
 * 文件名:    CommonViewHolder
 * 创建者:    cookie
 * 创建时间:   2020/1/11 23:25
 * 描述:      万能的ViewHolder
 */

public class CommonViewHolder extends RecyclerView.ViewHolder {

    //子View的集合

    private SparseArray<View> views;
    private View contentView;

    public CommonViewHolder(@NonNull View itemView) {
        super(itemView);
        views = new SparseArray<>();
        contentView = itemView;
    }

    //获取CommonViewHolder实体
    public static CommonViewHolder getViewHolder(ViewGroup parent, int layoutId) {
        return new CommonViewHolder(View.inflate(parent.getContext(), layoutId, null));
    }

    //提供给外部访问View的方法
    public <T extends View> T getView(int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = contentView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    //设置文本
    public CommonViewHolder setText(int viewId, String text) {
        TextView tv = getView(viewId);
        //tv.setWidth(350);
        tv.setText(text);
        return this;
    }

    //设置图片链接
    public CommonViewHolder setImageUrl(Context context, int viewId, String url) {
        ImageView iv = getView(viewId);
        GlideHelper.loadUrl(context, url, iv);
        return this;
    }

    //设置图片文件
    public CommonViewHolder setImageFile(Context context, int viewId, File imageFile) {
        ImageView iv = getView(viewId);
        GlideHelper.loadFile(context, imageFile, iv);
        return this;
    }

    //设置图片
    public CommonViewHolder setImageResource(int viewId, int resId) {
        ImageView iv = getView(viewId);
        iv.setImageResource(resId);
        return this;
    }

    //设置背景颜色
    public CommonViewHolder setBackgroundColor(int viewId, int color) {
        ImageView iv = getView(viewId);
        iv.setBackgroundColor(color);
        return this;
    }

    //设置文本颜色
    public CommonViewHolder setTextColor(int viewId, int color) {
        TextView tv = getView(viewId);
        tv.setTextColor(color);
        return this;
    }
}
